<template>
	<view class="rf-search-bar" :style="[{'color': titleTintColor}, bgColor]">
		<view
			class="header"
			:style="{width:merchantShow ? '100vw' : width+'px', paddingTop: merchantShow ? 0 : inputTop+'px'}"
		>
			<view class="uni_topbar" :style="style">
					<view class="inner flexbox flex_alignc" :class="[fixed ? 'fixed' : '']" :style="[{'height': customBarH + 'px','color': titleTintColor}, bgColor]">
							<!-- 返回 -->
							<!-- <text class="uni_icoBack iconfont icon-arrL" v-if="isBack" @tap="goBack"></text> -->
							<view v-if="isBack" @tap="goBack" style="position:absolute;left:15px">
									<slot name="back"></slot>
							</view>
							<slot name="headerL"></slot>
							<!-- 标题 -->
							<!-- #ifndef MP -->
							<view class="flex1" v-if="!search && center"></view>
							<!-- #endif -->
							<view class="uni_title flex1" style="text-align: center;" :class="[center ? 'uni_titleCenter' : '']" :style="[isBack ? {'font-size': '32upx', 'padding-left': '0'} : '']" v-if="!search && title">
									{{title}}
							</view>
							<view class="uni_search flex1" :class="[searchRadius ? 'uni_searchRadius' : '']" v-if="search"> />
									<input class="uni_searchIpt flex1" type="text" placeholder="搜索" placeholder-style="color: rgba(255,255,255,.5);" />
							</view>
							<!-- 右侧 -->
							<view class="uni_headerRight flexbox flex_row flex_alignc" style="position:absolute;right:15px">
									<slot name="iconfont"></slot>
									<slot name="string" ></slot>
									<slot name="image"></slot>
											<view class="header-menu" @click="toggleMenuDisplay">
															<view class="menu-bar"></view>
															<view class="menu-bar"></view>
															<view class="menu-bar"></view>
														</view>
							</view>
					</view>
			</view>
		</view>


		<!-- 多级弹出导航菜单 -->
		<view v-if="showMenu" class="nav-menu-mask" @click="toggleMenuDisplay" :style="[{'top': customBarH + 'px'}]">
		  <view class="nav-menu" @click.stop >
		    <!-- <view class="nav-menu-close" @click="showMenu = false">×</view> -->
		    <view class="nav-grid">
		      <view
		        v-for="(item, index) in menus"
		        :key="index"
		        class="nav-grid-item"
		        @click="cGo(item)"
		      >
		        <text>{{ item.title }}</text>
		      </view>
		    </view>
		  </view>
		</view>


	</view>
</template>

<script>
		import { indexList} from '@/api/product';
    export default {

        data() {
            return {
							merchantShow:0,
                statusBarH: this.StatusBar,
                customBarH: this.CustomBar,
								CustomBar: this.CustomBar,
								searchValue: this.placeholder,
								appLogo: this.$mSettingConfig.appLogo,
								isOpenScan: this.$mSettingConfig.isOpenScan,
								isOpenIndexCate: this.$mSettingConfig.isOpenIndexCate,
								height: 0,
								width: 0,
								inputTop: 0,
								tabCurrentIndex: 0,
								menus: [
								],
								showMenu: false,
								openMenuIndex: null,
								openSubMenuIndex: null,
								searchValue: '',
								showCharPicker: false,
								showImagePicker: false,
								specialChars: [
								  'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'κ', 'μ', 'ω', 'σ', 'τ', 'λ',
								  'Ⅰ', 'Ⅱ', 'Ⅲ', 'Ⅳ', 'Ⅴ', 'Ⅵ', 'Ⅶ', 'Ⅷ', 'Ⅸ', 'Ⅹ', 'Ⅺ',
								  'Ⅻ', 'X Ⅲ', 'X Ⅳ', 'X Ⅴ', 'X Ⅵ', 'X Ⅶ', 'X Ⅷ'
								],
								imageList: [
								  { src: '/static/images/pic1.png', name: '图片1' },
								  { src: '/static/images/pic2.png', name: '图片2' },
								  { src: '/static/images/pic3.png', name: '图片3' }
								]
            }
        },
				watch: {
						  // 监听对象具体的属性， deep就不需要设置为true了
						        statusBarH: {
						         handler (newName, oldName) {
											 console.log(newName)
															this.statusBarH = newName;
						            }
						        }

				},
        props: {
            isBack: { type: [Boolean, String], default: true },
            title: { type: String, default: '' },
            titleTintColor: { type: String, default: '#fff' },
            bgColor: Object,
            center: { type: [Boolean, String], default: false },
            search: { type: [Boolean, String], default: false },
            searchRadius: { type: [Boolean, String], default: false },
            fixed: { type: [Boolean, String], default: false },

        },
        computed: {
            style() {
                let _style = `height: ${this.customBarH}px;`
                return _style
            }
        },
				mounted(options) {
				   this.getIndexConfig()
				},
				created() {
					let obj = {};
					// #ifdef MP-WEIXIN
					// eslint-disable-next-line
					obj = wx.getMenuButtonBoundingClientRect();
					// #endif
					uni.getSystemInfo({
						success: (res) => {
							this.width = obj.left || res.windowWidth;
							this.height = obj.top ? (obj.top + obj.height + 8) : (res.statusBarHeight + 44);
							this.inputTop = obj.top ? (obj.top + (obj.height - 30) / 2) : (res.statusBarHeight );
						}
					});
				},
        methods: {
            goBack() {
                uni.navigateBack()
            },
						// 切换菜单显示/隐藏
						toggleMenuDisplay() {
							this.showMenu = !this.showMenu;
							// 如果隐藏菜单，同时重置子菜单状态
							if (!this.showMenu) {
								this.openMenuIndex = null;
								this.openSubMenuIndex = null;
							}
						},
						cGo(item) {
									const link = item.link || item.url;
									if (!link) return;
									try {
										// 标准化路径格式（去除前导/和查询参数）
										const normalizedLink = link.replace(/^\//, '').split('?')[0];

										// tabBar页面列表 - 从实际的pages.json同步更新
										const tabBarPages = [
											'pages/index/index',
											'pages/profile/profile'
										];

										// 判断是否为tabBar页面
										const isTabBarPage = tabBarPages.includes(normalizedLink);
										if (isTabBarPage) {

											console.log(1111)

											uni.switchTab({
												url: `/${normalizedLink}`,
												fail: (err) => {
													console.error('switchTab failed:', err);
													// 如果switchTab失败，回退到普通导航
													uni.navigateTo({ url: link });
												}
											});
										} else {
											uni.navigateTo({
												url: link,
												fail: (err) => {
													console.error('navigateTo failed:', err);
												}
											});
										}
									} catch (error) {
										console.error('Navigation error:', error);
										// 发生错误时尝试普通导航
										uni.navigateTo({ url: link });
									}
								},
						// 获取商品列表
						async getIndexConfig(type) {
							await this.$http
								.get(`${indexList}`, {})
								.then(async r => {
									this.loading = false;
									if (type === 'refresh') {
										uni.stopPullDownRefresh();
									}
							     this.menus = r.data.menus;;
								})
								.catch(err => {
									this.errorInfo = err;
									this.loading = false;
									if (type === 'refresh') {
										uni.stopPullDownRefresh();
									}
								});
						},
						toggleMenu(i) {
						  if (this.openMenuIndex === i) {
						    this.openMenuIndex = null;
						    this.openSubMenuIndex = null;
						  } else {
						    this.openMenuIndex = i;
						    this.openSubMenuIndex = null;
						  }
						},
						toggleSubMenu(j) {
						  if (this.openSubMenuIndex === j) {
						    this.openSubMenuIndex = null;
						  } else {
						    this.openSubMenuIndex = j;
						  }
						},
						onMenuClick(name) {
						  this.showMenu = false;
						  this.openMenuIndex = null;
						  this.openSubMenuIndex = null;
						  this.$emit('menu-click', name);
						},
						insertImageName(name) {
						  this.searchValue += name;
						},
						insertChar(char) {
						  this.searchValue += char;
						},
						onInputBlur() {
						  setTimeout(() => {
						    this.showCharPicker = false;
						  }, 100);
						},
						onSearch() {
						  const keyword = this.searchValue.trim();
						  console.log(keyword);
						  if (keyword) {
						    const url = `/pages/product/list?keyword=${encodeURIComponent(keyword)}`;
						    uni.navigateTo({
						        url: url
						    });

						  }
						}
        }
    }
</script>
<style>
	.rf-search-bar{	  }
	.uni_topbar{}
	.flexbox{display:flex;padding:10px}
	.flex1{flex:1}
	.uni_headerRight {padding:0}
.header-menu { width: 56rpx; height: 56rpx; display: flex; flex-direction: column; justify-content: center; align-items: center; }
.menu-bar { width: 36rpx; height: 5rpx; background: #e53935; margin: 4rpx 0; border-radius: 3rpx; }

	.nav-menu-mask {
	  position: fixed;
	  left: 0;
	  top: 0;
	  right: 0;
	  bottom: 0;
	  background: rgba(0,0,0,0.4);
	  z-index: 998;
	  display: flex;
	  justify-content: center;
	  align-items: flex-start;
	}

	.nav-menu {
	  width: 100%;
	  background: #fff;
	  padding: 20rpx;
	  border-radius: 0 0 20rpx 20rpx;
	  position: relative;

	  margin-top: 0;
	  max-height: 80vh;
	  overflow-y: auto;
	  transform: none !important;
	}

	@keyframes slideDown {
	  from {
	    transform: translateY(-100%);
	  }
	  to {
	    transform: translateY(0);
	  }
	}

	.nav-grid {
	  display: flex;
	  flex-wrap: wrap;
	  padding: 20rpx;
	  background: #fff;
	  box-sizing: border-box;
	  width: 100%;
	}

	.nav-grid-item {
	  background: #f5f5f5;
	  height: 80rpx;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  border-radius: 8rpx;
	  font-size: 26rpx;
	  color: #333;
	  padding: 8rpx;
	  box-sizing: border-box;
	  min-width: 0;
	  overflow: hidden;
	  text-overflow: ellipsis;
	  white-space: nowrap;
	  width: calc(25% - 15rpx);
	  margin: 0 7.5rpx 15rpx 7.5rpx;

	  &:active {
	    background: #e0e0e0;
	  }

	  text {
	    text-align: center;
	    width: 100%;
	    overflow: hidden;
	    text-overflow: ellipsis;
	    white-space: nowrap;
	  }
	}

	.nav-menu-close {
	  position: absolute;
	  top: 10rpx;
	  right: 10rpx;
	  width: 60rpx;
	  height: 60rpx;
	  line-height: 60rpx;
	  text-align: center;
	  font-size: 40rpx;
	  color: #999;
	  z-index: 1000;
	  background: rgba(0,0,0,0.1);
	  border-radius: 50%;
	}
	.nav-menu-item {
	  border-bottom: 1rpx solid #f0f0f0;
	}
	.nav-menu-main {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  padding: 32rpx 48rpx;
	  font-size: 32rpx;
	  color: #222;
	  cursor: pointer;
	}
	.arrow {
	  font-size: 28rpx;
	  color: #e53935;
	  margin-left: 12rpx;
	}
	.nav-sub-menu {
	  background: #fafafa;
	}
	.nav-sub-menu-item {
	  border-bottom: 1rpx solid #f0f0f0;
	}
	.nav-third-menu {
	  background: #f5f5f5;
	}
	.nav-third-menu-item {
	  padding: 28rpx 72rpx;
	  font-size: 28rpx;
	  color: #333;
	  cursor: pointer;
	}
	.nav-third-menu-item:active {
	  background: #f7f7f7;
	}
	.product-item:nth-child(2n+1):last-child {
	  flex-basis: 100%;
	  max-width: 100%;
	}

	</style>
